package mall

import (
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	"mall-go/common"
	"mall-go/dto"
	mall3 "mall-go/model"
	"mall-go/repository"
	"mall-go/response"
	"strconv"
	"strings"
)

type MallGoodsController struct {
	DB *gorm.DB
}

func NewMallGoodsController() MallGoodsController {
	db := common.GetDB()
	db.AutoMigrate(mall3.GoodsInfo{})
	return MallGoodsController{DB: db}
}

// GetCategories 获取分类数据
func (g MallGoodsController) GetCategories(ctx *gin.Context) {
	goodsRepo := repository.NewMallGoodsRepo()
	categories := goodsRepo.GetCategoriesForIndex()
	if len(categories) == 0 {
		response.Failure(ctx, nil, "数据不存在")
		return
	}
	response.Success(ctx, gin.H{
		"categories": categories,
	}, "Success")
}

// GoodsDetail 查询商品详情
func (g MallGoodsController) GoodsDetail(ctx *gin.Context) {
	goodsRepo := repository.NewMallGoodsRepo()
	goodsId, _ := strconv.Atoi(ctx.Params.ByName("goodsId"))
	if goodsId < 1 {
		response.Failure(ctx, nil, "参数异常")
		return
	}
	info := goodsRepo.GetNewBeeMallGoodsById(goodsId)
	if info.GoodsId == 0 {
		response.Failure(ctx, nil, "参数异常")
		return
	}
	if 0 != info.GoodsSellStatus {
		response.Failure(ctx, nil, "商品已下架")
		return
	}
	goodsInfoDTO := dto.GoodsInfoDTO{
		GoodsId:            info.GoodsId,
		GoodsName:          info.GoodsName,
		GoodsIntro:         info.GoodsIntro,
		GoodsCoverImg:      info.GoodsCoverImg,
		SellingPrice:       info.SellingPrice,
		Tag:                info.Tag,
		GoodsCarousel:      strings.Split(info.GoodsCarousel, ","),
		OriginalPrice:      info.OriginalPrice,
		GoodsDetailContent: info.GoodsDetailContent,
	}
	response.Success(ctx, gin.H{
		"goodsInfo": goodsInfoDTO,
	}, "SUCCESS")
}

// Search 商品搜索接口 状态0代表上架
func (g MallGoodsController) Search(ctx *gin.Context) {
	keyword := ctx.Query("keyword")
	goodsCategoryId, _ := strconv.Atoi(ctx.Query("goodsCategoryId"))
	orderBy := ctx.Query("orderBy")
	pageNumber, _ := strconv.Atoi(ctx.Query("pageNumber"))

	//参数校验
	if goodsCategoryId == 0 && keyword == "" {
		panic("非法搜索参数")
	}
	if pageNumber < 1 {
		pageNumber = 1
	}
	//封装搜索参数
	pageDTO := dto.GoodsPageDTO{
		GoodsCategoryId: goodsCategoryId,
		Page:            pageNumber,
		Limit:           10,
		Keyword:         keyword,
		OrderBy:         orderBy,
		GoodsSellStatus: 0,
		Start:           (pageNumber - 1) * 10,
	}
	goodsRepo := repository.NewMallGoodsRepo()
	goodsList := goodsRepo.SearchNewBeeMallGoods(pageDTO)
	response.Success(ctx, gin.H{"goodsPage": goodsList}, "Success")
}
